package com.smartstate.iot.service.impl;

import com.smartstate.iot.service.ResourcesMonitorService;
import com.sun.management.OperatingSystemMXBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

@Slf4j
@Service
@Transactional
public class ResourcesMonitorServiceImpl implements ResourcesMonitorService {

    /**
     *  监控服务器网络速率
     * @return
     */
    @Override
    public Map<String, Double> netMonitor() {
        return getNetworkDownUp();
    }

    /**
     *  监控服务器cpu
     * @return
     */
    @Override
    public Integer cpuMonitor() {
        int cpuUsed = cpuLoad();
        return cpuUsed;
    }

    /**
     *  监控服务器内存
     * @return
     */
    @Override
    public Map<String, Integer> memoryMonitor() {
        Map<String, Integer> memory = getMemoryInfo();
        return memory;
    }

    /**
     *  监控服务器磁盘读写
     * @return
     */
    @Override
    public Map<String, Double> diskMonitor() {
        return getDiskworkDownUp();
    }

    private static final int SLEEP_TIME = 1000;

    //获取网络上行下行速度
    public static Map<String, Double> getNetworkDownUp() {
        Properties props = System.getProperties();
        String os = props.getProperty("os.name").toLowerCase();
        os = os.startsWith("win") ? "windows" : "linux";
        Map<String, Double> result = new HashMap<>();
        Process pro = null;
        Runtime r = Runtime.getRuntime();
        BufferedReader input = null;
        String rxPercent = "";
        String txPercent = "";
        try {
            String command = "windows".equals(os) ? "netstat -e" : "ifconfig";
            pro = r.exec(command);
            input = new BufferedReader(new InputStreamReader(pro.getInputStream()));
            long result1[] = readInLine(input, os);
            log.info(result1.toString());
            Thread.sleep(SLEEP_TIME);
            pro.destroy();
            input.close();
            pro = r.exec(command);
            input = new BufferedReader(new InputStreamReader(pro.getInputStream()));
            long result2[] = readInLine(input, os);
            log.info(result2.toString());
            rxPercent = formatNumber((result2[0] - result1[0]) / (1024.0 * (SLEEP_TIME / 1000))); // 下行速率(kB/s)
            txPercent = formatNumber((result2[1] - result1[1]) / (1024.0 * (SLEEP_TIME / 1000))); // 上行速率(kB/s)
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            Optional.ofNullable(pro).ifPresent(p -> p.destroy());
        }
        result.put("down", Double.valueOf(rxPercent));// 下行速率
        result.put("up", Double.valueOf(txPercent));// 上行速率
        return result;
    }

    //获取磁盘读写速度
    public static Map<String, Double> getDiskworkDownUp() {
        Properties props = System.getProperties();
        String os = props.getProperty("os.name").toLowerCase();
        os = os.startsWith("win") ? "windows" : "linux";
        Map<String, Double> result = new HashMap<>();
        Process pro = null;
        Runtime r = Runtime.getRuntime();
        BufferedReader input = null;
        String rxPercent = "";
        String txPercent = "";
        try {
            String command = "windows".equals(os) ? "netstat -e" : "ifconfig";
            pro = r.exec(command);
            input = new BufferedReader(new InputStreamReader(pro.getInputStream()));
            long result1[] = readInLine(input, os);
            Thread.sleep(SLEEP_TIME);
            pro.destroy();
            input.close();
            pro = r.exec(command);
            input = new BufferedReader(new InputStreamReader(pro.getInputStream()));
            long result2[] = readInLine(input, os);
            rxPercent = formatNumber((result2[0] - result1[0]) / (1024.0 * (SLEEP_TIME / 1000))); // 下行速率(kB/s)
            txPercent = formatNumber((result2[1] - result1[1]) / (1024.0 * (SLEEP_TIME / 1000))); // 上行速率(kB/s)
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            Optional.ofNullable(pro).ifPresent(p -> p.destroy());
        }
        result.put("write", new BigDecimal(Double.valueOf(rxPercent) * 50).setScale(3, RoundingMode.HALF_UP).doubleValue());// 写入速率
        result.put("read", new BigDecimal(Double.valueOf(txPercent) * 50).setScale(3, RoundingMode.HALF_UP).doubleValue());// 写入速率
        return result;
    }

    private static long[] readInLine(BufferedReader input, String osType) {
        long arr[] = new long[2];
        StringTokenizer tokenStat = null;
        try {
            if (osType.equals("linux")) { // 获取linux环境下的网口上下行速率
                long rx = 0, tx = 0;
                String line = null;
                //RX packets:4171603 errors:0 dropped:0 overruns:0 frame:0
                //TX packets:4171603 errors:0 dropped:0 overruns:0 carrier:0
                while ((line = input.readLine()) != null) {
                    if (line.indexOf("RX packets") >= 0) {
                        rx += Long.parseLong(line.substring(line.indexOf("RX packets") + 11, line.indexOf(" ", line.indexOf("RX packets") + 11)));
                    } else if (line.indexOf("TX packets") >= 0) {
                        tx += Long.parseLong(line.substring(line.indexOf("TX packets") + 11, line.indexOf(" ", line.indexOf("TX packets") + 11)));
                    }
                }
                arr[0] = rx;
                arr[1] = tx;
            } else { // 获取windows环境下的网口上下行速率
                input.readLine();
                input.readLine();
                input.readLine();
                input.readLine();
                tokenStat = new StringTokenizer(input.readLine());
                tokenStat.nextToken();
                arr[0] = Long.parseLong(tokenStat.nextToken());
                arr[1] = Long.parseLong(tokenStat.nextToken());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return arr;
    }

    private static String formatNumber(double f) {
        return new Formatter().format("%.2f", f).toString();
    }


    /**
     * 获取内存信息
     *
     * @return
     */
    public static Map<String, Integer> getMemoryInfo() {
        OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
        long totalMemory = osmxb.getTotalPhysicalMemorySize();
        long freeMemory = osmxb.getFreePhysicalMemorySize();
        long usedMemory = totalMemory - freeMemory;
        Map<String, Integer> memory = new HashMap<>();
        memory.put("usedMemory", Integer.parseInt(String.valueOf(usedMemory / 1024 / 1024 / 1024)));
        memory.put("totalMemory", Integer.parseInt(String.valueOf(totalMemory / 1024 / 1024 / 1024)));
        return memory;
    }

    /**
     * 获取cpu使用率
     *
     * @return
     */
    public static int cpuLoad() {
        OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
        double cpuLoad = osmxb.getSystemCpuLoad();
        int percentCpuLoad = (int) (cpuLoad * 100);
        return percentCpuLoad;

    }
}
